package com.xtayfjpk.zookeeper.test.master_workers.callback.recovery;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;

import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseChildrenCallback;
import com.xtayfjpk.zookeeper.test.master_workers.recovery.RecoveredAssignments;
import com.xtayfjpk.zookeeper.test.master_workers.recovery.RecoveryCallback;

public class RecoveryWorkersCallback extends BaseChildrenCallback {
	private final static Logger LOGGER = Logger.getLogger(RecoveryWorkersCallback.class);
	private RecoveredAssignments assignments;
	
	
	public RecoveryWorkersCallback(RecoveredAssignments recoveredAssignments) {
		this.assignments = recoveredAssignments;
	}


	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			List<String> children) {
		assignments.getWorkers(ctx);
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, List<String> children) {
		LOGGER.info("Getting worker assignments for recovery: " + children.size());
		
		/**
		 * No worker available yet, so the master is probably let's just return an empty list.
		 */
		if(children.size()==0) {
			LOGGER.warn( "Empty list of workers, possibly just starting" );
			assignments.getCb().recoveryComplete(RecoveryCallback.OK, new ArrayList<String>());
		} else {
			assignments.setActiveWorkerList(children);
			for(String sw : assignments.getAssignedWorkerList()) {
				assignments.getWorkerAssignments("/assign/" + sw);
			}
		}
		
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			List<String> children) {
		LOGGER.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
		assignments.getCb().recoveryComplete(RecoveryCallback.FAILED, null);
	}
}
